package com.yx.system.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.yx.common.annotation.AuthIgnore2;
import com.yx.common.annotation.Log;
import com.yx.common.annotation.LoginUser2;
import com.yx.common.utils.PageUtils;
import com.yx.common.utils.Query;
import com.yx.common.utils.R;
import com.yx.common.validator.Assert;
import com.yx.modules.api.entity.TbVolume;
import com.yx.modules.api.service.TbVolumeService;
import com.yx.system.entity.*;
import com.yx.system.service.TdBookService;
import com.yx.system.service.TdSectionService;
import com.yx.system.service.TdTextService;
import com.yx.system.service.impl.TdTextServiceImpl;
import com.yx.utils.*;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.rmi.server.UID;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 章节控制器
 */
@RestController
@RequestMapping("/sys/section")
public class TdSectionController2 {

    @Autowired
    private TdSectionService tdSectionService;

    @Autowired
    private TdTextServiceImpl tdTextService;

    @Autowired
    private TdBookService tdBookService;

    @Autowired
    private TbVolumeService tbVolumeService;

    /**
     * 按ID查询
     *
     * @return
     */
    @Log("按ID查询")
    @RequestMapping("/findById/{id}")
    @RequiresPermissions("sys:section:findById")
    public R findById(@PathVariable("id") int id) {
        Map<String, Object> map = new HashMap<>();
        TdSection tdSection = tdSectionService.selectByPrimaryKey(id);
        map.put("section", tdSection);
        map.put("context", tdTextService.findByInfo(tdSection.getUuid()));
        return R.ok().put("map", map);
    }

    /**
     * 新增或修改
     *
     * @return
     */
    @Log("新增或修改")
    @PostMapping("save")
    @RequiresPermissions("sys:section:save")
    public R saveOrUpdate(String id, MultipartFile filetext, String sectionname, Integer bookid, String bookPrice, Integer volumeId,@LoginUser2 SysUser sysUser) throws IOException {
        Assert.isBlank(sectionname,"请输入章节名");
        if (volumeId.equals("")){
            return R.error("请选择所属卷");
        }
        if (sysUser.getIdentity()==1 && Integer.parseInt(AmountUtils.changeY2F(bookPrice))>0){
            return R.error("签约作者才能收费");
        }
        TdSection tdSection = new TdSection();
        if (Integer.parseInt(AmountUtils.changeY2F(bookPrice))!=0){
            tdSection.setSectionType(1);
        }else {
            tdSection.setSectionType(0);
        }
        String regex = "[\u4e00-\u9fff]";
        //根据volumeId查询卷
        TbVolume tbVolume = tbVolumeService.queryObject(volumeId);
        if (id.equals("")) {
            tdSection.setBookid(bookid);
            tdSection.setCreatedate(new Date());
            tdSection.setIsdelete(false);
            tdSection.setVolumeId(tbVolume.getId());
            tdSection.setVolumeName(tbVolume.getVolumeName());
            tdSection.setCreateuser(sysUser.getUsername());
            tdSection.setUpdatedate(new Date());
            tdSection.setUpdateuser(sysUser.getUsername());
            tdSection.setTotalfee(Integer.parseInt(AmountUtils.changeY2F(bookPrice)));
            tdSection.setSectionname(sectionname);
            tdSection.setSectionno((int) Math.random());
            tdSection.setUuid(UidUtil.getUUID());
            int tdSectionId = tdSectionService.insert(tdSection);
            tdSectionService.selectByPrimaryKey(tdSectionId);
            //查询书籍信息
            TdBook tdBook = tdBookService.selectByPrimaryKey(tdSection.getBookid());
            tdBook.setNewsection(tdSection.getSectionname());
            tdBook.setNewsectionid(tdSection.getId());
            if (tdSection.getTotalfee()>0){
                tdBook.setIspay(true);
            }
            tdBookService.updateByPrimaryKey(tdBook);
            //实例文本对象，并赋值
            TdText tdText = new TdText();
            tdText.setAuthor(tdBook.getAuthorName());
            tdText.setBookname(tdBook.getBookname());
            tdText.setCreatetime(new Date());
            tdText.setIsdelete(0);
            tdText.setUid(tdSection.getUuid());
            tdText.setSection(tdSection.getSectionname());
//          读取文件中得内容，并且赋值给文本对象
            tdText.setText(ContextUtil.fileReadUtil(filetext));
            tdText.setId(UidUtil.getUUID());
            int count =(" " + ContextUtil.fileReadUtil(filetext) + " ").split (regex).length - 1;
            //执行保存操作
            tdTextService.saveText(tdText);
            tdSection.setFontsize(count);
            tdSectionService.updateByPrimaryKey(tdSection);
        } else {
            tdSection = tdSectionService.selectByPrimaryKey(Integer.parseInt(id));
            tdSection.setVolumeId(tbVolume.getId());
            tdSection.setVolumeName(tbVolume.getVolumeName());
            tdSection.setBookid(bookid);
            tdSection.setUpdatedate(new Date());
            tdSection.setUpdateuser(sysUser.getUsername());
            tdSection.setTotalfee(Integer.parseInt(AmountUtils.changeY2F(bookPrice)));
            tdSection.setSectionname(sectionname);
            tdSection.setSectionno((int) Math.random());
            tdSectionService.updateByPrimaryKey(tdSection);
            //查询书籍信息
            TdBook tdBook = tdBookService.selectByPrimaryKey(tdSection.getBookid());
            if (filetext != null && !filetext.equals("")) {
                //获取文件上传后的访问地址
                TdText tdText = null;
                tdText = tdTextService.findByInfo(tdSection.getUuid());
                //实例文本对象，并赋值
                tdText.setAuthor(tdBook.getAuthorName());
                tdText.setBookname(tdBook.getBookname());
                tdText.setCreatetime(new Date());
                tdText.setIsdelete(0);
                tdText.setUid(tdSection.getUuid());
                tdText.setSection(tdSection.getSectionname());
                //将上传后的文件传入文件对象
                //读取文件中得内容，并且赋值给文本对象
                tdText.setText(ContextUtil.fileReadUtil(filetext));
                int count =(" " + ContextUtil.fileReadUtil(filetext) + " ").split (regex).length - 1;
                //执行更新操作
                tdTextService.updateText(tdText);
                tdSection.setFontsize(count);
                tdSectionService.updateByPrimaryKey(tdSection);
            }
        }
        return R.ok();
    }

    /*
    *
    */
    @Log("作者写书")
    @RequestMapping("saveByAuthor")
    @RequiresPermissions("sys:section:saveByAuthor")
    public R saveByAuthor(String text1,String sectionname, Integer bookid, String bookPrice, Integer volumeId,@LoginUser2 SysUser sysUser) throws UnsupportedEncodingException {

        Assert.isBlank(text1,"内容不能为空");
        Assert.isBlank(bookPrice,"价格不能为空");
        Assert.isBlank(sectionname,"章节名不能为空");
        Assert.isNull(bookid,"图书标识不能为空");
        Assert.isNull(volumeId,"章节所属分类不能为空");
        String text=new String(Base64.decodeBase64(text1),"utf-8");
        if (sysUser.getIdentity()==1 && Integer.parseInt(AmountUtils.changeY2F(bookPrice))>0){
            return R.error("签约作者才能收费");
        }
        TdSection tdSection = new TdSection();
        if (Integer.parseInt(AmountUtils.changeY2F(bookPrice))!=0){
            tdSection.setSectionType(1);
        }else {
            tdSection.setSectionType(0);
        }
        String regex = "[\u4e00-\u9fff]";
        //根据volumeId查询卷
        TbVolume tbVolume = tbVolumeService.queryObject(volumeId);
        tdSection.setBookid(bookid);
        tdSection.setCreatedate(new Date());
        tdSection.setIsdelete(false);
        tdSection.setVolumeId(tbVolume.getId());
        tdSection.setVolumeName(tbVolume.getVolumeName());
        tdSection.setCreateuser(sysUser.getUsername());
        tdSection.setUpdatedate(new Date());
        tdSection.setUpdateuser(sysUser.getUsername());
        tdSection.setTotalfee(Integer.parseInt(AmountUtils.changeY2F(bookPrice)));
        tdSection.setSectionname(sectionname);
        tdSection.setSectionno((int) Math.random());
        tdSection.setUuid(UidUtil.getUUID());
        int tdSectionId = tdSectionService.insert(tdSection);
        tdSectionService.selectByPrimaryKey(tdSectionId);
        //查询书籍信息
        TdBook tdBook = tdBookService.selectByPrimaryKey(tdSection.getBookid());
        tdBook.setNewsection(tdSection.getSectionname());
        tdBook.setNewsectionid(tdSection.getId());
        if (tdSection.getTotalfee()>0){
            tdBook.setIspay(true);
        }
        tdBookService.updateByPrimaryKey(tdBook);
        //实例文本对象，并赋值
        TdText tdText = new TdText();
        tdText.setAuthor(tdBook.getAuthorName());
        tdText.setBookname(tdBook.getBookname());
        tdText.setCreatetime(new Date());
        tdText.setIsdelete(0);
        tdText.setUid(tdSection.getUuid());
        tdText.setSection(tdSection.getSectionname());
        //读取文件中得内容，并且赋值给文本对象
        tdText.setText(text);
        tdText.setId(UidUtil.getUUID());
        int count =(" " + text + " ").split (regex).length - 1;
        //执行保存操作
        tdTextService.saveText(tdText);
        tdSection.setFontsize(count);
        tdSectionService.updateByPrimaryKey(tdSection);
        return R.ok();
    }
    /**
     * 删除(软删除)
     *
     * @return
     */
    @Log("删除章节(软删除)")
    @PostMapping("delete")
    @RequiresPermissions("sys:section:delete")
    public R delete(@RequestBody Integer[] ids) {
        for (int i = 0; i < ids.length; i++) {
            int id = ids[i];
            TdSection tdSection = tdSectionService.selectByPrimaryKey(id);
            tdSection.setIsdelete(true);
            tdSectionService.updateByPrimaryKey(tdSection);
        }
        return R.ok();
    }

    /**
     * 查询所有
     *
     * @param map
     * @return
     */
    @Log("查询所有")
    @PostMapping("findAllByCondition")
    @RequiresPermissions("sys:section:findAllByCondition")
    public R findAllByCondition(@RequestParam Map<String, Object> map) {
        Query query = new Query(map);
        Page<TdSection> pageUtil = new Page<TdSection>(query.getPage(), query.getLimit());
        Page<TdSection> page = tdSectionService.queryPageList(pageUtil, query);
        return R.ok().put("page", page);
    }

    }
